﻿using System;
using System.Buffers;

using Microsoft.Extensions.DependencyInjection;
using Xc.DataAccess.Core.Extensions;
namespace Xc.DataAccess.PcpChannels
{
    /// <summary>
    /// 应答数据
    /// </summary>
    public  class RespondFrame : Frame
    {
        public RespondFrame(byte [] dataarea)
        {
            this.IsValidate = false;
            SequenceReader<byte> sequenceReader = new SequenceReader<byte>(new ReadOnlySequence<byte>(dataarea));
            ReadOnlyMemory<byte> readOnlyMemory=new ReadOnlyMemory<byte>(Start.FromUInt16BigEndian());
            if (!sequenceReader.TryReadTo(out ReadOnlySequence<byte> seq, readOnlyMemory.Span))
            {
                return;
            }
            if (!sequenceReader.TryRead(out var v))
            {
                return;
            }
            Version = v;
            if (!sequenceReader.TryRead(out var m))
            {
                return;
            }
            MessageCode = (MessageCode)m;
            if (ValidateMessageCode!=null)
            {
                if (MessageCode != ValidateMessageCode)
                {
                    return;
                }
            }
            if (!sequenceReader.TryReadUInt16BigEndian(out var chekc))
            {
                return;
            }
            CheckCode = chekc;
            if (!sequenceReader.TryReadUInt16BigEndian(out var length))
            {
                return;
            }
            DataAreaLength = length;
            if (!sequenceReader.TryRead(DataAreaLength,out var dataArea))
            {
                return;
            }
            var reader = new SequenceReader<byte>(dataArea);
            IsValidate = SetDataArea(ref reader);
        }
        /// <summary>
        /// 起始标致
        /// </summary>
        internal ushort Start { get; set; } = 0xFFFE;
        /// <summary>
        /// 版本号
        /// </summary>
        internal byte Version { get; set; }
        /// <summary>
        /// 消息码
        /// </summary>
        public MessageCode MessageCode { get; set; }
        /// <summary>
        /// 要校验的数据
        /// </summary>
        /// <returns></returns>
        protected virtual MessageCode? ValidateMessageCode { get; } = null;

        /// <summary>
        /// 校验码
        /// </summary>
        internal ushort CheckCode { get; set; }
        /// <summary>
        /// 数据域长度
        /// </summary>
        internal ushort DataAreaLength { get; set; }
        /// <summary>
        /// 数据域数据
        /// </summary>
        protected virtual bool SetDataArea(ref SequenceReader<byte> dataArea) { return true; }

    }
}
